<template>
  <div>
    <div class="search-container">
      <div class="search-inp-container">
        <el-input @keyup.enter.native="handleSearch" placeholder="输入订单编号" v-model="listQuery.orderId" style="width:210px" clearable>
        </el-input>
        <el-input @keyup.enter.native="handleSearch" placeholder="输入买家手机号" v-model="listQuery.userMobile" style="width:170px" clearable>
        </el-input>

          <!--<el-select class="filter-item w347" v-model="listQuery.orderSourceid" placeholder="请选择渠道商" style="width:170px" clearable>-->
            <!--<el-option v-for="item in channelOptions" :key="item.channelId" :label="item.channelName" :value="item.channelId" >-->
              <!--<span style="float: left">{{ item.channelName }}</span>-->
            <!--</el-option>-->
          <!--</el-select>-->

        <el-select @keyup.enter.native="handleSearch" v-model="listQuery.orderStatus" placeholder="选择订单状态" style="width:180px" clearable >
          <el-option v-for="item in recomMaps" :key="item.key" :label="item.name" :value="item.key" >
            <span style="float: left">{{ item.name }}</span>
          </el-option>
        </el-select>
        <el-date-picker
          v-model="listQuery.startDate"
          type="date"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd" style="width:200px"
          placeholder="选择开始时间">
        </el-date-picker>
        <el-date-picker
          v-model="listQuery.endDate"
          type="date"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd" style="width:200px"
          placeholder="选择结束时间">
        </el-date-picker>
        <!--<el-input @keyup.enter.native="handleSearch" placeholder="开始时间" v-model="listQuery.startDate" style="width:170px" clearable>-->
        <!--</el-input>-->
        <!--<el-input @keyup.enter.native="handleSearch" placeholder="结束时间" v-model="listQuery.endDate" style="width:170px" clearable>-->
        <!--</el-input>-->
      </div>
      <el-button class="search-btn" type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
      <!--<el-button class="search-btn" type="primary" icon="el-icon-plus" @click="handleAdd">添加</el-button>-->
      <el-button class="search-btn" :autofocus="true" icon="el-icon-refresh" @click="refreshHandle">刷新</el-button>

      <!--<el-button class="search-btn" v-if="mall_order_export" :autofocus="true" icon="el-icon-refresh" @click="exportExl">批量导出</el-button>-->

    </div>
    <div class="search-container">
      <el-button  v-if="mall_order_export" class="search-btn" :autofocus="true" icon="el-icon-refresh" @click="exportExl">批量导出</el-button>
    </div>
    <el-table :key='tableKey' :data="list" v-loading="listLoading" border fit highlight-current-row>
      <el-table-column align="center" prop="orderId" label="订单号">
      </el-table-column>
      <!--<el-table-column align="center" prop="channelName" label="商户名称" >-->
      <!--</el-table-column>-->
      <el-table-column align="center" prop="goodName" label="商品名称">
      </el-table-column>
      <el-table-column align="center" prop="remarks" label="商品规格">
      </el-table-column>
      <el-table-column align="center" prop="coreSum" label="积分">
        <template slot-scope="scope">
          <span>{{scope.row.coreSum/100}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="rechargeNum" label="数量">
      </el-table-column>
      <el-table-column align="center" prop="pice" label="订单金额">
        <template slot-scope="scope">
          <span>{{scope.row.pice/100}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center"  prop="name"  label="姓名">
        <template slot-scope="scope">
          <span>{{noPassByName(scope.row.name) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="userMobile" label="用户手机号">
      </el-table-column>
      <el-table-column align="center" prop="orderStatus" label="订单状态">
        <template slot-scope="scope">
          <el-span >
            {{scope.row.orderStatus | statusFilter}}
          </el-span>

        </template>
      </el-table-column>

      <el-table-column align="center" label="下单时间">
        <template slot-scope="scope">
          <span>{{scope.row.orderDate | parseTime('{y}-{m}-{d} {h}:{i}')}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="180" v-if="mall_order_update" >
        <template slot-scope="scope">
          <!--<el-button v-if="sys_user_update" size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>-->
          <!--<el-button v-if="sys_user_delete" size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>-->
          <el-button v-if="mall_order_update" size="mini" type="primary" @click="handleUpdate(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.current" :page-size="listQuery.size" :page-sizes="[10, 40, 80, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="40%" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="订单编号" prop="orderId">
          <el-input class="w347" disabled="disabled" v-model="form.orderId" placeholder="" readonly="readonly"></el-input>
        </el-form-item>

        <!--<el-form-item label="渠道商" prop="orderSourceid">
          <el-input class="w347" disabled="disabled" autocomplete="off" v-model="form.orderSourceid" placeholder="" readonly="readonly"></el-input>
        </el-form-item>-->

        <el-form-item label="商品名" prop="goodName">
          <el-input class="w300"  disabled="disabled" v-model="form.goodName" placeholder="" readonly="readonly"></el-input>
        </el-form-item>

        <el-form-item label="用户手机号" prop="userMobile">
          <el-input  class="w300" disabled="disabled" autocomplete="off" v-model="form.userMobile" placeholder="" readonly="readonly"></el-input>
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select class="filter-item w347" v-model="form.orderStatus" placeholder="请选择" >
            <el-option v-for="item in recomMaps" :key="item.key" :label="item.name" :value="item.key" :disabled="isDisabled[item.delFlag]">
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">修 改</el-button>
      </div>
    </el-dialog>


  </div>

</template>

<script>
import { fetchList, delObj, getObj, addObj, putObj, exportOrder } from '@/api/mallorder'
import { getTopDictListByDescNew } from '@/api/dict'
import { getChannelList } from '@/api/channel'
import { mapGetters } from 'vuex'
export default {
  data() {
    return {

      tableKey: 0,
      listLoading: false,
      list: [],
      listQuery: {
        current: 1,
        size: 10,
        orderSource: 2, // 来源：商城
        orderId: '',
        userMobile: '',
        //orderSourceName: '',
        startDate: '',
        endDate: '',
        orderStatus: '',
        orderSourceid: '',
      },
      total: 0,
      mall_order_export: false,
      mall_order_update: false,
      sys_user_delete: false,
      sys_user_select: false,
      dialogFormVisible: false,
      form: {
        username: undefined,
        password: undefined,
        delFlag: undefined,
        mobile: undefined,
        role: []
      },
      recomMaps: [
        // {
        //   key: '0',
        //   name: '待兑换'
        // },
        {
          key: '1',
          name: '兑换成功'
        },
        {
          key: '2',
          name: '兑换失败'
        },
        {
          key: '3',
          name: '正在兑换'
        }
      ],
      form1: {
        goodName: undefined
      },
      rules: {
        username: [
          {
            required: true,
            message: '请输入账户',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '账号长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 20,
            message: '密码长度在 6 到 20 个字符',
            trigger: 'blur'
          }
        ],
        deptId: [
          {
            required: true,
            message: '请选择部门',
            trigger: 'blur'
          }
        ],
        role: [
          {
            required: true,
            message: '请选择角色',
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '手机号不能为空',
            trigger: 'blur'
          },
          {
            min: 11,
            max: 11,
            message: '手机号长度为11',
            trigger: 'blur'
          }
        ]
      },
      textMap: {
        update: '编辑',
        create: '创建'
      },
      dialogStatus: '',
      role: [],
      orderStatusOptions: [],
      orderCheckStatusOptions: [],
      channelOptions: [],
      isDisabled: {
        0: false,
        1: true
      },
      statusOptions: ['0', '1'],
      dialogDeptVisible: false,
      treeDeptData: [],
      checkedKeys: [],
      defaultProps: {
        children: 'childrens',
        label: 'name'
      }
    }
  },

  components: {},
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: '待兑换',
        1: '兑换成功',
        2: '兑换失败',
        3: '正在兑换'
      }
      return statusMap[status]
    }
  },
  computed: {
    ...mapGetters(['permissions'])
  },

  mounted() {
    this.getList()
    this.getChannel()
    this.mall_order_export = this.permissions['/mall/order:export']
    this.mall_order_update = this.permissions['/mall/order:update']
    this.sys_user_delete = this.permissions['/admin/user:delete']
    this.sys_user_select = this.permissions['/admin/user:select']
  },

  methods: {
    // 姓名脱敏
    noPassByName(str) {
      if (str != null && str != undefined) {
        if (str.length <= 3) {
          return '*' + str.substring(1, str.length)
        } else if (str.length > 3 && str.length <= 6) {
          return '**' + str.substring(2, str.length)
        } else if (str.length > 6) {
          return str.substring(0, 2) + '****' + str.substring(6, str.length)
        }
      } else {
        return ''
      }
    },
    getList() {
      this.getOrderStatusList()
      this.listLoading = true
      this.listQuery.isAsc = false
      fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    refreshHandle() {
      this.listQuery.current = 1
      this.listQuery.size = 10
      this.listQuery.username = ''
      this.getList()
      this.getChannel()
      // this.getOrderStatusList()
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      // this.getDictList()
      getObj(row.orderId).then(response => {
        this.form = response.data.orderQuery
        this.form.goodName = response.data.orderDatails.goodName
        this.dialogFormVisible = true
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
      })
    },
    handleSearch() {
      this.listQuery.current = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.current = val
      this.getList()
    },

    cancel(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    update(formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false
          this.form.password = undefined
          putObj(this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    // async getDictList() {
    //   const res = await getTopDictListByDescNew('订单状态')
    //   this.orderCheckStatusOptions = res.data
    // },
    async getOrderStatusList() {
      // const res = await getTopDictListByDescNew('订单状态')
      // this.orderStatusOptions = res.data
      getTopDictListByDescNew('订单状态').then(res => {
        this.orderStatusOptions = res.data
      })
    },
    async getChannel() {
      const res = await getChannelList()
      this.channelOptions = res.data
    },
    exportExl: function() {
      var _this = this
      if (_this.list.length < 1) {
        _this.$message({
          type: 'error',
          message: '暂无数据无法导出'
        })
        return
      }
      _this.listLoading = true
      exportOrder(this.listQuery).then(response => {
        const data = response
        const url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        const now = new Date() // 时间戳为10位时，需要乘1000
        const year = now.getFullYear()
        const month = (now.getMonth() + 1) > 9 ? now.getMonth() + 1 : '0' + (now.getMonth() + 1)
        const date = now.getDate() > 9 ? now.getDate() : '0' + now.getDate()
        link.setAttribute('download', year + '-' + month + '-' + date + '订单信息导出.xls')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        _this.listLoading = false
      })
    }
  }
}

</script>


<style lang='scss' scoped>
.w347 {
  width: 100%;
}
</style>
